package github.ziwukun.jsonql.lang;

import java.util.LinkedList;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

public class SelectItemImpl implements SelectItem{
	private static final long serialVersionUID = -7629241620633458064L;
	String prop;
	Select childs;
	
	SelectItemImpl(String prop,Select childs){
		this.prop = prop;
		this.childs = childs;
		asserts();
	}
	
	@Override
	public String prop() {
		return prop;
	}

	@Override
	public Select childs() {
		return childs;
	}

	@Override
	public boolean isChildEmpty() {
		return childs.isItemsEmpty();
	}

	@Override
	public SelectItem repProp(String propName) {
		return new SelectItemImpl(propName, 
			ObjectUtil.cloneByStream(childs));
	}

	@Override
	public SelectItem repChilds(Select child) {
		SelectItemImpl repOne = ObjectUtil.cloneByStream(this);
		child = ObjectUtil.cloneByStream(child);
		repOne.childs = child;
		
		return repOne;
	}
	
	@Override
	public String toJSONQL() {
		return SelectItemJson.writeJson(this);
	}
	
	private void asserts() {
		if(StrUtil.isBlank(prop)) {
			throw new JSONQLBuildException("搜索项属性明能不能为空字符串");
		}
		if(CmpOpr.isCmpOpr(prop)) {
			throw new JSONQLBuildException("搜索项属名不能为比较符号");
		}
		if(childs == null) {
			childs = new SelectImpl(new LinkedList<>());
		}
	}
}
